package com.taotao.trolley.controller;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.taoato.sso.service.UserLoginService;
import com.taotao.common.pojo.TaotaoResult;
import com.taotao.common.util.CookieUtils;
import com.taotao.common.util.JsonUtils;
import com.taotao.pojo.TbItem;
import com.taotao.pojo.TbUser;
import com.taotao.service.ItemService;
import com.taotao.trolley.service.CartService;

/**
 * 购物车controller
 * 
 * @author Administrator
 *
 */
@Controller
public class CartController {

	// 引入商品服务
	@Autowired
	private ItemService itemService;

	// 引入购物车服务
	@Autowired
	private CartService cartService;

	// 引入用户登录的服务
	@Autowired
	private UserLoginService userService;

	@Value("${TOKEN_KEY}")
	private String TOKEN_KEY;

	@Value("${CART_KEY}")
	private String CART_KEY;

	// localhost:8090/cart/add/${item.id}.html
	@RequestMapping(value = "/cart/add/{itemId}", method = RequestMethod.GET)
	public String addCartById(@PathVariable Long itemId, Integer num, HttpServletRequest request,
			HttpServletResponse response) {
		// 调用商品服务，根据id获得商品
		TbItem tbItem = itemService.getItemById(itemId);
		// 获得Cookies中的token
		String token = CookieUtils.getCookieValue(request, TOKEN_KEY);
		// 根据token获取用户信息
		TaotaoResult result = userService.getToken(token);

		// 判断用户是否登录
		if (result.getStatus() == 200) {// 登录
			TbUser user = (TbUser) result.getData();
			cartService.addItemCart(tbItem, num, user.getId());
		} else {// 没登录
				// 获取cookie中的商品列表
			List<TbItem> cartList = getCookieCartList(request);
			// 判断购物车内是否有同款商品
			boolean flag = false;

			Iterator<TbItem> iterator = cartList.iterator();
			while (iterator.hasNext()) {
				TbItem tbItem2 = (TbItem) iterator.next();
				if (tbItem2.getId() == itemId) {
					tbItem2.setNum(tbItem2.getNum() + num);
					flag = true;
					break;
				}
			}
			// 如果购物车内存在同类商品,需要设置回cookie中
			if (flag) {
				CookieUtils.setCookie(request, response, CART_KEY, JsonUtils.objectToJson(cartList), 7 * 24 * 3600,
						true);
			} else {
				tbItem.setNum(num);
				// 判断是否有商品图片
				if (StringUtils.isNotBlank(tbItem.getImage())) {
					tbItem.setImage(tbItem.getImage().split(",")[0]);
				}
				cartList.add(tbItem);
				// 设置回cookies中
				CookieUtils.setCookie(request, response, CART_KEY, JsonUtils.objectToJson(cartList), 7 * 24 * 3600,
						true);
			}

		}

		return "cartSuccess";
	}

	// $.post("/cart/update/num/"+_thisInput.attr("itemId")+"/"+_thisInput.val()
	// +".action"
	@RequestMapping(value = "/cart/update/num/{itemId}/{num}", method = RequestMethod.POST)
	@ResponseBody
	public TaotaoResult updateNum(@PathVariable long itemId, @PathVariable Integer num, HttpServletRequest request,
			HttpServletResponse response) {
		// 获得Cookies中的token
		String token = CookieUtils.getCookieValue(request, TOKEN_KEY);
		// 根据token获取用户信息
		TaotaoResult result = userService.getToken(token);

		// 判断用户是否登录
		if (result.getStatus() == 200) {// 登录调用service方法
			TbUser user = (TbUser) result.getData();
			cartService.updateCartByUserId(user.getId(), itemId, num);
		} else {// 只需更新cookie中的数据
			updateCookieCart(request, response, itemId, num);
		}
		return TaotaoResult.ok();
	}

	// $.post("/cart/delete/"+_thisInput.attr("itemId")+ ".html"
	// 删除商品
	@RequestMapping(value = "/cart/delete/{itemId}", method = RequestMethod.POST)
	public TaotaoResult deleteCartItem(@PathVariable long itemId, HttpServletRequest request,
			HttpServletResponse response) {

		// 获得Cookies中的token
		String token = CookieUtils.getCookieValue(request, TOKEN_KEY);
		// 根据token获取用户信息
		TaotaoResult result = userService.getToken(token);
		// 判断用户是否登录
		if (result.getStatus() == 200) {// 登录的话调用service层方法
			TbUser user = (TbUser) result.getData();
			cartService.deleteCartItemById(user.getId(), itemId);
		} else {
			List<TbItem> list = getCookieCartList(request);
			boolean flag = false;
			Iterator<TbItem> iterator = list.iterator();
			while (iterator.hasNext()) {
				TbItem tbItem = (TbItem) iterator.next();
				if (tbItem.getId() == itemId) {
					flag = true;
					iterator.remove();
				}
			}

			CookieUtils.setCookie(request, response, CART_KEY, JsonUtils.objectToJson(list), 7 * 24 * 3600, true);
		}
		return TaotaoResult.ok();
	}

	// -----------------------------------取得购物车列表----------------------------
	// href="http:localhost:8090/cart/cart.html"
	@RequestMapping("cart/cart")
	public String showCart(Model model, HttpServletRequest request) {

		// 获得Cookies中的token
		String token = CookieUtils.getCookieValue(request, TOKEN_KEY);
		// 根据token获取用户信息
		TaotaoResult result = userService.getToken(token);

		// 判断用户是否登录
		if (result.getStatus() == 200) {// 登录从redis中获取
			TbUser user = (TbUser) result.getData();
			List<TbItem> cartList = cartService.getCartList(user.getId());
			model.addAttribute("cartList", cartList);
		} else {// 没登录的话从cookie中获取
			String cookieValue = CookieUtils.getCookieValue(request, CART_KEY, true);
			List<TbItem> cartList = getCookieCartList(request);
			model.addAttribute("cartList", cartList);
		}
		return "cart";
	}

	// 获取cookie购物车的列表
	public List<TbItem> getCookieCartList(HttpServletRequest request) {
		// 从cookie中获取商品列表
		String cookieValue = CookieUtils.getCookieValue(request, CART_KEY, true);
		// 判断购物册是否为空
		if (StringUtils.isNotBlank(cookieValue)) {
			List<TbItem> list = JsonUtils.jsonToList(cookieValue, TbItem.class);
			return list;
		}
		return new ArrayList<>();
	}

	// 更新cookie中商品列表
	private void updateCookieCart(HttpServletRequest request, HttpServletResponse response, long itemId, Integer num) {
		// 获得cookie中的商品列表
		String cookieValue = CookieUtils.getCookieValue(request, CART_KEY, true);

		if (null != cookieValue) {
			List<TbItem> list = JsonUtils.jsonToList(cookieValue, TbItem.class);
			Iterator<TbItem> iterator = list.iterator();
			while (iterator.hasNext()) {
				TbItem tbItem = (TbItem) iterator.next();
				if (tbItem.getId() == itemId) {
					tbItem.setNum(num);
				}
			}
			// 从新设置回cookie中
			CookieUtils.setCookie(request, response, CART_KEY, JsonUtils.objectToJson(list), 7 * 24 * 3600, true);
		}
	}

}
